package org.springframework.cloud.openfeign;

import com.mrzhou.web.feign.CloudSentienlFeign;
import com.mrzhou.web.interceptor.FeignRequestHeaderInterceptor;
import com.mrzhou.web.props.CloudWebProperties;
import com.mrzhou.web.strategy.HystrixConcurrencyRequestContextStrategy;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import feign.Feign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;

/**
 * feign配置
 * 自定义{@link Targeter}, 因其类不是public修饰的类,所以只能创建相同的包来解决此问题
 */
@Configuration
public class CloudFeignConfiguration {

    @Autowired
    private CloudWebProperties cloudWebProperties;

    /**
     * 重新设置Hystrix策略, 主要调整 {@link HystrixConcurrencyRequestContextStrategy}
     * 防止在{@link FeignRequestHeaderInterceptor}因Hystrix在不同线程时无法获取request的问题
     *
     */
    @PostConstruct
    public void init() {
        HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
        HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
        HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy();
        HystrixCommandExecutionHook commandExecutionHook = HystrixPlugins.getInstance().getCommandExecutionHook();
        HystrixPlugins.reset();
        HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
        HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
        HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
        HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
        HystrixPlugins.getInstance().registerConcurrencyStrategy(new HystrixConcurrencyRequestContextStrategy());
    }

    /**
     * Feign设置请求头拦截器
     */
    @Bean
    public FeignRequestHeaderInterceptor requestInterceptor() {
        return new FeignRequestHeaderInterceptor(cloudWebProperties);
    }

    @Bean
    @ConditionalOnProperty(name = "feign.sentinel.enabled")
    public Feign.Builder feignBuilder() {
        return CloudSentienlFeign.builder();
    }

    @Bean
    @Primary
    @ConditionalOnProperty(name = "feign.hystrix.enabled")
    public Targeter hystrixTargeter() {
        return new CloudHystrixTarget();
    }

}
